import { Directive } from 'vue'
import { watch } from 'vue'
import { ElLoading } from 'element-plus'

// 自定义指令
// 存储 Element 到 Loading 实例的映射
const loadingEl = new WeakMap<HTMLElement, ReturnType<typeof ElLoading.service> | undefined>()

// 存储 Element 到 Watch 停止函数的映射
const watchEl = new WeakMap<HTMLElement, (() => void) | undefined>()

export const vMyLoading: Directive<HTMLElement> = {
  beforeMount(el, { value }) {
    let store = value
    let unwatch = watch(
      (): number => store.view.value.status,
      (status: number) => {
        if (status === 1) {
          // 激活loading效果
          let loadingInstance: ReturnType<typeof ElLoading.service> | undefined = loadingEl.get(el)
          const targetEl = el.querySelector('.el-table__body-wrapper') as HTMLElement
          loadingInstance
            ? loadingInstance
            : (loadingInstance = ElLoading.service({
                target: targetEl,
                background: 'rgba(255, 255, 255, 1)',
                text: '加载中...'
              }))

          // 存储实例
          loadingEl.set(el, loadingInstance)
        } else {
          // 调用关闭方法
          let loadingInstance: ReturnType<typeof ElLoading.service> | undefined | null = loadingEl.get(el)
          loadingInstance?.close()
          // 清空引用 避免出现重复的实例
          loadingEl.delete(el)
          loadingInstance = null
        }
      }
    )

    // 存储watch
    watchEl.set(el, unwatch)
  },
  unmounted(el) {
    let unwatch: Function | undefined = watchEl.get(el)
    if (unwatch) {
      unwatch()
      // 清空引用
      watchEl.delete(el)
    }
  }
}
